//
//  XXHomeSearchViewController.m
//  XiuXiuTuanGou
//
//  Created by 王克博 on 2019/5/11.
//  Copyright © 2019 XiuXiuTuanGou. All rights reserved.
//

#import "MeatSearchViewController.h"
#import "FMTagsView.h"
//#import "XXHomeShopDetailViewController.h"
//
//#import "XXHomeListTableViewCell.h"
//#import "XXTGNHomeErrorOrEmptyTableViewCell.h"  //数据为空展示cell
//
//#import "XXNetWorking+Home.h"


@interface MeatSearchViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, FMTagsViewDelegate>

@property (strong, nonatomic) UIView * navView;
@property (strong, nonatomic) UITextField * searchTextField;
@property (strong, nonatomic) UIButton * cancelButton;

@property (strong, nonatomic) UITableView * tableView;
//@property (strong, nonatomic) XXHomeModel * model;
@property (strong, nonatomic) NSMutableArray * dataArray;

@property (assign, nonatomic) NSInteger page;

@property (assign, nonatomic) BOOL isGetDataSuccess; //是否获取数据失败

@property (strong, nonatomic) UIScrollView * scrollView;
@property (strong, nonatomic) UILabel * historyTitleLabel;
@property (strong, nonatomic) UIButton * historyDeleteButton;
@property (strong, nonatomic) FMTagsView * historyTagView;      //历史搜索记录

@property (strong, nonatomic) UILabel * hotTitleLabel;
@property (strong, nonatomic) FMTagsView * hotTagView;          //热门搜索

@property (strong, nonatomic) NSMutableArray * historyArray;
@property (strong, nonatomic) NSMutableArray * hotArray;

@property (assign, nonatomic) BOOL isNotNeedSaveHistory;    //是否不需要保存历史搜索记录

@end

@implementation MeatSearchViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:self.searchTextField];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _isNotNeedSaveHistory = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.baseNavView.hidden = NO;
//    self.baseNavView.leftNavBtn.hidden = NO;
//    kWeakSelf(self)
//    self.baseNavView.leftBlock = ^{
//        [weakself dismissViewControllerAnimated:YES completion:^{
//        }];
//    };
//    self.baseNavView.line.hidden = YES;
//    self.baseNavView.navTitleLabel.text = @"店铺搜索";
    
    self.view.backgroundColor = KWhiteColor;
    
    _dataArray = [NSMutableArray array];
    _page = 1;
    
    _historyArray = [NSMutableArray array];
    _hotArray = [NSMutableArray array];
    
    _isNotNeedSaveHistory = NO;
    
    //[self initArrayData];
    
    [self createUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChanged:) name:UITextFieldTextDidChangeNotification object:self.searchTextField];
}

//创建UI
- (void)createUI
{    
    [self.view addSubview:self.navView];
    [self.searchTextField becomeFirstResponder];
    [self.view addSubview:self.scrollView];
   // [self reloadTagsView];
}

//赋值 刷新
- (void)reloadTagsView
{
    float historyViewBottom;
    if (self.historyArray.count > 0) {
        self.historyTitleLabel.hidden = NO;
        self.historyDeleteButton.hidden = NO;
        self.historyTagView.hidden = NO;
        self.historyTagView.tagsArray = self.historyArray;
       // float height = [self getFMTagViewHeight:self.historyTagView];
        //self.historyTagView.height = height;
        historyViewBottom = self.historyTagView.bottom+30;
    }else {
        self.historyTitleLabel.hidden = YES;
        self.historyDeleteButton.hidden = YES;
        self.historyTagView.hidden = YES;
        historyViewBottom = 30;
    }
    if (self.hotArray.count > 0) {
        self.hotTitleLabel.hidden = NO;
        self.hotTagView.hidden = NO;
        self.hotTagView.tagsArray = self.hotArray;
        self.hotTitleLabel.top = historyViewBottom;
        self.hotTagView.top = self.hotTitleLabel.bottom+15;
        //float height = [self getFMTagViewHeight:self.hotTagView];
       // self.hotTagView.height = height;
        self.scrollView.contentSize = CGSizeMake(KScreenWidth, self.hotTagView.bottom+30);
    }else {
        self.hotTitleLabel.hidden = YES;
        self.hotTagView.hidden = YES;
        if (self.historyTagView.hidden != YES) {
            self.scrollView.contentSize = CGSizeMake(KScreenWidth, self.historyTagView.bottom+30);
        }else {
            self.scrollView.contentSize = CGSizeMake(KScreenWidth,self.scrollView.height);
        }
    }
    
}

//- (float)getFMTagViewHeight:(FMTagsView *)tagsView
//{
//    CGSize contentSize = tagsView.collectionView.collectionViewLayout.collectionViewContentSize;
//    return contentSize.height;
//}
//
//- (void)initArrayData
//{
//    //获取缓存的历史记录
//    if ([kUserDefaults arrayForKey:kUserSearchHistory]) {
//        [_historyArray addObjectsFromArray:[kUserDefaults arrayForKey:kUserSearchHistory]];
//    }
//    //根据首页传入数据 筛选出热门数组
//    if (_hotWords && _hotWords.count > 0) {
//        for (int i = 0; i<_hotWords.count; i++) {
//            XXHomeHotWordsModel * model = _hotWords[i];
//            [_hotArray addObject:model.title];
//        }
//    }
//}

////MARK: - request
//- (void)needReloadData
//{
//    _page = 1;
//    XXNetWorking * manager = [XXNetWorking sharedInstance];
//    kWeakSelf(self)
//    if (_dataArray.count > 0) {
//        [_dataArray removeAllObjects];
//    }
//    [manager getHomeDataWithAction:@"0" cid:@"" keyword:_searchTextField.text CallBack:^(BOOL isSucessed, id outParam, NSString *eMsg) {
//        [weakself.tableView.mj_header endRefreshing];
//        if (isSucessed == YES) {
//            weakself.isGetDataSuccess = YES;
//            weakself.model = [XXHomeModel modelWithJSON:outParam];
//            if (weakself.model.data.stores) {
//                [weakself.dataArray addObjectsFromArray:weakself.model.data.stores];
//            }
//            if (weakself.model.data.stores.count < 10) {
//                weakself.tableView.mj_footer = nil;
//            }
//            if (weakself.model.data.stores.count == 10) {
//                if (weakself.tableView.mj_footer == nil) {
//                    [weakself setupFooterRefresh];
//                }
//            }
//        }else {
//            weakself.isGetDataSuccess = NO;
//        }
//        [weakself.tableView reloadData];
//    }];
//}
//
//
//- (void)needReloadMoreData
//{
//    _page++;
//    XXNetWorking * manager = [XXNetWorking sharedInstance];
//    kWeakSelf(self)
//    [manager getHomeMoreDataWithAction:@"0" cid:@"" keyword:_searchTextField.text page:_page CallBack:^(BOOL isSucessed, id outParam, NSString *eMsg) {
//        [weakself.tableView.mj_footer endRefreshing];
//        if (isSucessed == YES) {
//            XXHomeModel * model = [XXHomeModel modelWithJSON:outParam];
//            if (model.data.stores) {
//                [weakself.dataArray addObjectsFromArray:model.data.stores];
//            }
//            if (model.data.stores.count < 10) {
//                weakself.tableView.mj_footer = nil;
//            }
//        }
//        [weakself.tableView reloadData];
//    }];
//}

//MARK: - FMTagsViewDelegate
- (void)tagsView:(FMTagsView *)tagsView didSelectTagAtIndex:(NSUInteger)index
{
//    if (!_tableView) {
//        [self.view addSubview:self.tableView];
//    }
//    if (_tableView.hidden != NO) {
//        _tableView.hidden = NO;
//    }
//    if (tagsView == self.historyTagView) {
//        if (index < self.historyArray.count) {
//            NSString * keyword = self.historyArray[index];
//            if (keyword) {
//                self.searchTextField.text = keyword;
//                [self needReloadData];
//            }
//        }
//    }else if (tagsView == self.hotTagView) {
//        if (index < self.hotArray.count) {
//            NSString * keyword = self.hotArray[index];
//            if (keyword) {
//                self.searchTextField.text = keyword;
//                [self needReloadData];
//            }
//        }
//    }
}

//MARK: - textfield delegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    //如果键盘取消 需要将当前搜索内容当做搜索记录保存
    if (textField == self.searchTextField) {
        if (_isNotNeedSaveHistory != YES) {
            if (self.searchTextField.text.length > 0) {
                if ([kUserDefaults arrayForKey:kUserSearchHistory]) {
                    NSArray * array = [kUserDefaults arrayForKey:kUserSearchHistory];
                    
                    for (NSString *str in array) {
                        if ([str isEqualToString:self.searchTextField.text]) {
                            //判断 当前搜索字段已包含则直接退出 不处理
                            return;
                        }
                    }
                    
                    NSMutableArray * newArray = [NSMutableArray arrayWithArray:array];
                    //如果数组为10条 需要删除1条 再插入一条，限制最多10条
                    if (newArray.count >= 10) {
                        [newArray removeLastObject];
                    }
                    [newArray insertObject:self.searchTextField.text atIndex:0];
                    NSArray * lastArray = [NSArray arrayWithArray:newArray];
                    [kUserDefaults setObject:lastArray forKey:kUserSearchHistory];
                    [kUserDefaults synchronize];
                }else {
                    NSArray * array = [NSArray arrayWithObject:self.searchTextField.text];
                    [kUserDefaults setObject:array forKey:kUserSearchHistory];
                    [kUserDefaults synchronize];
                }
                if (_historyArray.count >= 10) {
                    [_historyArray removeLastObject];
                }
                [_historyArray insertObject:self.searchTextField.text atIndex:0];
                [self reloadTagsView];
            }
        }else {
            _isNotNeedSaveHistory = NO;
        }
    }
}

//MARK: - tableview delegate/dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_dataArray.count == 0) {
        return 1;
    }
    return _dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataArray.count == 0) {
       // return KScreenHeight-self.navView.bottom-XXTG_SafeAreaBottomHeight;
    }
    return 112;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.searchTextField resignFirstResponder];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (_dataArray.count == 0) {
//        XXTGNHomeErrorOrEmptyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"XXTGNHomeErrorOrEmptyTableViewCell"];
//        [cell updataWithIsError:!_isGetDataSuccess emptyMsg:@"未搜索到相关店铺"];
//        kWeakSelf(self)
//        cell.clickReloadButtonBlock = ^{
//            [weakself needReloadData];
//        };
//        return cell;
//    }
//    XXHomeListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XXHomeListTableViewCell"];
//    if (indexPath.row < _dataArray.count) {
//        XXHomeStoresModel * model = _dataArray[indexPath.row];
//        [cell updataWithModel:model];
//    }
    return [UITableViewCell new];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    [self.searchTextField resignFirstResponder];
//    if (indexPath.row < _dataArray.count) {
//        XXHomeStoresModel * model = _dataArray[indexPath.row];
//        kWeakSelf(self)
//        [self dismissViewControllerAnimated:YES completion:^{
//            if (weakself.choosedCellBlock) {
//                weakself.choosedCellBlock(model);
//            }
//        }];
//    }
}

//MARK: - event
- (void)textFieldTextDidChanged:(NSNotification *)notification
{
    //输入款内容改变通知
    if (!_tableView) {
        [self.view addSubview:self.tableView];
    }
    UITextField * textField = notification.object;
    if (textField == self.searchTextField) {
        if (textField.text.length == 0) {
            [_dataArray removeAllObjects];
            [_tableView reloadData];
            _tableView.hidden = YES;
        }else {
            _tableView.hidden = NO;
           // [self needReloadData];
        }
    }
}

- (void)clickCancelButton
{
    self.searchTextField.text = @"";
    [self.searchTextField resignFirstResponder];
    [_dataArray removeAllObjects];
    _tableView.hidden = YES;
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)clickHistoryDeleteButton
{
    //删除搜索历史
    UIAlertController * alertView = [UIAlertController alertControllerWithTitle:@"是否删除搜索记录？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    kWeakSelf(self)
    UIAlertAction * sureAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        if ([kUserDefaults arrayForKey:kUserSearchHistory]) {
            [kUserDefaults setObject:nil forKey:kUserSearchHistory];
            [kUserDefaults synchronize];
            [weakself.historyArray removeAllObjects];
            [weakself reloadTagsView];
        }
    }];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertView addAction:sureAction];
    [alertView addAction:cancelAction];
    [self presentViewController:alertView animated:YES completion:^{
    }];
}

//MARK: - getter
- (UIView *)navView
{
    if (!_navView) {
        _navView = [UIView makeViewBgColor:KWhiteColor cornerRadius:0];
        _navView.frame = CGRectMake(0, TJ_StatusBarHeight_Define, KScreenWidth, 44);
        

        //18
        UIView *searchView = [UIView makeViewBgColor:UIColorFromRGB(0xF7F7F7) cornerRadius:17];
        searchView.frame = CGRectMake(15, 3, KScreenWidth-15-58, 34);
        [_navView addSubview:searchView];

        UIImageView *searchImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 34, 34)];
        searchImgView.image = [UIImage imageNamed:@"meat_buy_search"];
        searchImgView.contentMode = UIViewContentModeCenter;
        [searchView addSubview:searchImgView];

        [searchView addSubview:self.searchTextField];
        [_navView addSubview:self.cancelButton];
        self.cancelButton.centerY = searchView.centerY;
    }
    return _navView;
}


- (UITextField *)searchTextField
{
    if (!_searchTextField) {
        _searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(34, 0, KScreenWidth-15-34-80, 34)];
        _searchTextField.placeholder = @"输入店铺名或者部位进行搜索";
        _searchTextField.delegate = self;
        _searchTextField.textColor = UIColorFromRGB(0xB2B2B2);
        _searchTextField.font = mFont(14);
    }
    return _searchTextField;
}

- (UIButton *)cancelButton
{
    if (!_cancelButton) {
        _cancelButton = [UIButton makeButtonWithText:@"取消" textColor:UIColorFromRGB(0x666666) font:mFont(14) textAliment:1 cornerRadius:0];
        _cancelButton.frame = CGRectMake(KScreenWidth-78, 0, 80, 44);
        [_cancelButton addTarget:self action:@selector(clickCancelButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.navView.bottom, KScreenWidth, KScreenHeight-self.navView.bottom-TJ_SafeAreaBottomHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = KWhiteColor;
//        [_tableView registerNib:[UINib nibWithNibName:@"XXHomeListTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"XXHomeListTableViewCell"];
//        [_tableView registerClass:[XXTGNHomeErrorOrEmptyTableViewCell class] forCellReuseIdentifier:@"XXTGNHomeErrorOrEmptyTableViewCell"];
        [self setupHeaderRefresh];
        [self setupFooterRefresh];
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}


- (void)setupHeaderRefresh
{
    if (_tableView.mj_header == nil) {
        MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(needReloadData)];
        _tableView.mj_header = header;
    }
}
- (void)setupFooterRefresh
{
    if (_tableView.mj_footer == nil) {
        MJRefreshAutoFooter * footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(needReloadMoreData)];
        _tableView.mj_footer = footer;
    }
}

- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, self.navView.bottom, KScreenWidth, KScreenHeight-self.navView.bottom-TJ_SafeAreaBottomHeight)];
        _scrollView.delegate = self;
        
        [_scrollView addSubview:self.historyTitleLabel];
        [_scrollView addSubview:self.historyDeleteButton];
        [_scrollView addSubview:self.historyTagView];
        
        [_scrollView addSubview:self.hotTitleLabel];
        [_scrollView addSubview:self.hotTagView];
    }
    return _scrollView;
}

- (UILabel *)historyTitleLabel
{
    if (!_historyTitleLabel) {
        _historyTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 30, 100, 25)];
        _historyTitleLabel.text = @"搜索历史";
        _historyTitleLabel.textColor = UIColorFromRGB(0x666666);
        _historyTitleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    }
    return _historyTitleLabel;
}

- (UIButton *)historyDeleteButton
{
    if (!_historyDeleteButton) {
        _historyDeleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _historyDeleteButton.frame = CGRectMake(KScreenWidth-60-15, self.historyTitleLabel.top-5, 60, 35);
        [_historyDeleteButton setTitle:@"清除" forState:UIControlStateNormal];
        [_historyDeleteButton setTitleColor:UIColorFromRGB(0x666666) forState:UIControlStateNormal];
        _historyDeleteButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_historyDeleteButton addTarget:self action:@selector(clickHistoryDeleteButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _historyDeleteButton;
}

- (FMTagsView *)historyTagView
{
    if (!_historyTagView) {
        _historyTagView  = [[FMTagsView alloc] initWithFrame:CGRectMake(15, self.historyTitleLabel.bottom+15, KScreenWidth - 30, 150)];
        _historyTagView.contentInsets = UIEdgeInsetsZero;
        _historyTagView.tagInsets = UIEdgeInsetsMake([self fitSize:6],
                                               [self fitSize:15],
                                               [self fitSize:6],
                                               [self fitSize:15]);
        _historyTagView.tagFont = [UIFont systemFontOfSize:[self fitSize:14]];
        _historyTagView.tagBorderWidth = 1;
        _historyTagView.tagcornerRadius = 3;
        _historyTagView.lineSpacing = 10;
        _historyTagView.interitemSpacing = 10;
        _historyTagView.backgroundColor = mBackgroudColor;
        _historyTagView.tagBorderColor = UIColorFromRGB(0xF5F5F5);
        _historyTagView.tagSelectedBorderColor = UIColorFromRGB(0xF5F5F5);
        _historyTagView.tagBackgroundColor = UIColorFromRGB(0xeeeeee);
        _historyTagView.tagSelectedBackgroundColor = UIColorFromRGB(0xeeeeee);
        _historyTagView.tagTextColor = UIColorFromRGB(0x666666);
        _historyTagView.tagSelectedTextColor = UIColorFromRGB(0x666666);
        _historyTagView.delegate = self;
    }
    return _historyTagView;
}


- (UILabel *)hotTitleLabel
{
    if (!_hotTitleLabel) {
        _hotTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, self.historyTagView.bottom+30, 100, 25)];
        _hotTitleLabel.text = @"热门搜索";
        _hotTitleLabel.textColor = UIColorFromRGB(0x666666);
        _hotTitleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    }
    return _hotTitleLabel;
}

- (FMTagsView *)hotTagView
{
    if (!_hotTagView) {
        _hotTagView  = [[FMTagsView alloc] initWithFrame:CGRectMake(15, self.hotTitleLabel.bottom+15, KScreenWidth - 30, 150)];
        _hotTagView.contentInsets = UIEdgeInsetsZero;
        _hotTagView.tagInsets = UIEdgeInsetsMake([self fitSize:6],
                                                     [self fitSize:15],
                                                     [self fitSize:6],
                                                     [self fitSize:15]);
        _hotTagView.tagFont = [UIFont systemFontOfSize:[self fitSize:14]];
        _hotTagView.tagBorderWidth = 1;
        _hotTagView.tagcornerRadius = 3;
        _hotTagView.lineSpacing = 10;
        _hotTagView.interitemSpacing = 10;
        _hotTagView.backgroundColor = mBackgroudColor;
        _hotTagView.tagBorderColor = UIColorFromRGB(0xF5F5F5);
        _hotTagView.tagSelectedBorderColor = UIColorFromRGB(0xF5F5F5);
        _hotTagView.tagBackgroundColor = UIColorFromRGB(0xeeeeee);
        _hotTagView.tagSelectedBackgroundColor = UIColorFromRGB(0xeeeeee);
        _hotTagView.tagTextColor = UIColorFromRGB(0x666666);
        _hotTagView.tagSelectedTextColor = UIColorFromRGB(0x666666);
        _hotTagView.delegate = self;
    }
    return _hotTagView;
}


@end
